package com.ideaction.game.xmldata;

import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Component;

import com.ideaction.game.utils.XmlParserKit;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class SampleContainer<V extends ISample> {

	private String filePath = "xmlconfig";
	protected Map<Class<V>, Map<Integer, V>> sampleMap = new HashMap<>();
	private static Map<String, Class<? extends ISample>> definedClassMap = new HashMap<>();

	public static void registDefinedClass(String className, Class<? extends ISample> clazz) {
		definedClassMap.put(className, clazz);
	}

	@SuppressWarnings("unchecked")
	public <T> T getSample(Class<? extends ISample> clazz, int sid) {
		Map<Integer, V> map = sampleMap.get(clazz);
		if (map == null) {
			return null;
		}
		return (T) map.get(sid);
	}

	/**
	 * 重载
	 * @param xmldataConfig
	 * @param fileName
	 */
	public void reload(String xmldataConfig, String fileName) {
		File file = new File(xmldataConfig + File.separator + fileName);
		xmlDataLoad(file, new SAXReader());
	}

	/**
	 * 加载全部配置
	 * 
	 * @throws FileNotFoundException
	 */
	public void load() throws FileNotFoundException {
		sampleMap.clear();
		File file = new File(filePath);
		File[] files = file.listFiles();
		SAXReader reader = new SAXReader();
		for (File f : files) {
			xmlDataLoad(f, reader);
		}
	}

	@SuppressWarnings("unchecked")
	private void xmlDataLoad(File f, SAXReader reader) {
		try {
			Document document = reader.read(f);
			Element root = document.getRootElement();
			List<Element> elements = root.elements();
			for (Element e : elements) {
				String clazzName = e.getName();
				V sample = null;
				Class<? extends ISample> clazz = definedClassMap.get(clazzName);
				sample = (V) clazz.newInstance();
				int sid = 0;
				for (Field field : clazz.getDeclaredFields()) {
					String fieldName = field.getName();
					Object value = e.attributeValue(fieldName);
					if (value != null) {
						field.setAccessible(true);
						field.set(sample, XmlParserKit.convertType(field.getType(), value));
						if (fieldName.equalsIgnoreCase("sid")) {
							sid = field.getInt(sample);
						}
					}
				}
				if (sid > 0) {
					Map<Integer, V> clazzmap = sampleMap.computeIfAbsent((Class<V>) clazz, (key) -> new HashMap<>());
					clazzmap.put(sid, sample);
					ISample isample = sample;
					isample.init();
				} else {
					log.error("sid <=0   clazzName:" + clazzName);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}
}
